package com.huaxindata.im.main.contactview.group;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;

import com.huaxin.common.utils.ToastUtil;
import com.huaxin.common.view.avatarimageview.AvatarImageView;
import com.huaxindata.im.R;
import com.huaxindata.im.constants.ImConstants;
import com.huaxindata.im.model.contact.Contact;
import com.huaxindata.im.util.Log;
import com.huaxindata.im.view.CharBar;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 该类是在创建群之前选择群成员对象的activity
 * 或者邀请好友进群选择好友
 */

public class SelectGroupMemberActivity extends
        AppCompatActivity implements CharBar.LetterChangeListener, AdapterView.OnItemClickListener {
    public static final String TAG = "SelectGroupMemberActivity";

    private Toolbar  mToolbar;
    private ListView mListView;
    private CharBar  mCharBar;
    private TextView mStickTv;//用于显示吸顶效果字母
    private TextView mSelectedNum;//已选择人数
    private Button   mSelectConfirmBtn;

    //数据集声明部分
    private List<Contact>           mContactList;//可供选择的联系人
    private Map<String, Integer>    mCharIndexMap;
    private Map<Integer, Boolean>   mCheckedPosition;//用这个来记录已经选中的位置
    private List<Contact>           mSelectedContacts;//已经选中的联系人
    private SelectMemberListAdapter mAdapter;

    private String mTip;//提示选择的多少人的字符串
    private int function = 0;//标记这个选择群成员是建群还是更新群成员

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_group_member);
        initView();
        initData();
    }

    public void initView() {
        mToolbar = (Toolbar) findViewById(R.id.select_group_member_toolbar);
        mListView = (ListView) findViewById(R.id.select_group_member_list);
        mCharBar = (CharBar) findViewById(R.id.select_group_member_charBar);
        mStickTv = (TextView) findViewById(R.id.select_group_member_stickTv);
        mSelectedNum = (TextView) findViewById(R.id.select_group_member_hint);
        mSelectConfirmBtn = (Button) findViewById(R.id.select_group_member_confirm);
        setSupportActionBar(mToolbar);
        mToolbar.setTitle("选择群成员");

        mAdapter = new SelectMemberListAdapter(this);
        mListView.setAdapter(mAdapter);
        mListView.setOnItemClickListener(this);
        mCharBar.setLetterChangeListener(this);
        mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                updateOrClearHeader(firstVisibleItem);
            }
        });
        mTip = getResources().getString(R.string.new_group_select);
        mSelectedContacts = new ArrayList<>();
        mSelectedNum.setText(String.format(mTip, mSelectedContacts.size()));
    }

    /**
     * 获取可以选择的好友
     */
    public void initData() {
        Intent intent = getIntent();
        function = intent.getIntExtra(ImConstants.FUNCTION_SELECT_GROUP_MEMBER, 0);
        if (mCharIndexMap == null) {
            mCharIndexMap = new HashMap<>();
        }
        if (mCheckedPosition == null) {
            mCheckedPosition = new HashMap<>();
        }
        //获取可以选择的联系人
        mContactList = SelectMemberPresenter.getSelectableMember();
        if (mContactList == null) {
            return;
        }
        List<Object> list = processData();
        mAdapter.setData(list);
        mAdapter.notifyDataSetChanged();
    }

    /**
     * 对联系人数据进行处理，使数据集合中含有按拼音首字母分组的字符
     *
     * @return
     */
    private List<Object> processData() {
        final List<Object> dataList = new ArrayList<>();
        Collections.sort(mContactList);
        mCharIndexMap.clear();
        for (Contact contact : mContactList) {
            String s = contact.getFirstName();
            if (!mCharIndexMap.containsKey(s)) {
                dataList.add(s);
                //记录了某字母首次出现的位置
                mCharIndexMap.put(s, dataList.size() - 1);
            }
            dataList.add(contact);
        }
        return dataList;
    }

    /**
     * 此处实现的是一个分组吸顶的效果，根据滑动的第一个可见项
     * 来判断是否更换字母，如果第一个可见的是字母，则更换字母显示
     *
     * @param firstVisibleItem
     */
    private void updateOrClearHeader(int firstVisibleItem) {
        //在listView第一项不显示这个吸顶的TextView
        if (firstVisibleItem == 0) {
            mStickTv.setVisibility(View.GONE);
            return;
        }
        final Object o = mAdapter.getData().get(firstVisibleItem);
        if (o instanceof String) {
            mStickTv.setVisibility(View.VISIBLE);
            mStickTv.setText(o.toString());
        }
    }

    /**
     * 每选中一个群成员后，更新显示选中的群成员的总数
     */
    private void updateSelectedNum() {
        if (mSelectedContacts == null) {
            return;
        }
        int size = mSelectedContacts.size();
        if (size > 0) {
            mSelectConfirmBtn.setEnabled(true);
            mSelectedNum.setText(String.format(mTip, size));
        } else {
            mSelectConfirmBtn.setEnabled(false);
        }
    }

    /**
     * 选择好群成员之后点击确认
     * 1、如果是创建群的话则要进入到CreateGroupActivity
     * 2、如果是在GroupInfoActivity中邀请好友进入到这个界面的话 三个人才能建群
     * 则要关闭这个界面，并传回数据
     *
     * @param v
     */
    public void onSelectConfirm(View v) {
        Log.e("lwjing", "selectContact size:" + mSelectedContacts.size());

        if (function == ImConstants.FUNCTION_ADD_MEMBER) {
            if (mSelectedContacts.size() > 0) {
                SelectMemberPresenter.setSelectedList(mSelectedContacts);
                setResult(ImConstants.FUNCTION_ADD_MEMBER);
                finish();
            } else {
                ToastUtil.showToast("请选择至少1个群成员");
            }
            return;
        }
        if (function == ImConstants.FUNCTION_DELETE_MEMBER) {
            if (mSelectedContacts.size() > 0) {
                SelectMemberPresenter.setSelectedList(mSelectedContacts);
                setResult(ImConstants.FUNCTION_DELETE_MEMBER);
                finish();
            } else {
                ToastUtil.showToast("请选择至少1个群成员");
            }
            return;
        }

        if (mSelectedContacts.size() > 1) {
            SelectMemberPresenter.setSelectedList(mSelectedContacts);
            Intent intent = new Intent(this, CreateGroupActivity.class);
            startActivityForResult(intent, ImConstants.REQUEST_CODE);
        } else {
            ToastUtil.showToast("请选择至少2名群成员");
        }
    }

    /**
     * 处理导航栏返回按扭点击事件
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        if (itemId == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onLetterChanged(String s) {
        if (mCharIndexMap.containsKey(s)) {
            final int val = mCharIndexMap.get(s);
            mListView.setSelection(val);
            updateOrClearHeader(mListView.getFirstVisiblePosition());
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        List<Object> data = mAdapter.getData();
        Object object = data.get(position);
        if (object instanceof Contact) {
            boolean isChecked = isChecked(position);
            Contact contact = (Contact) object;
            if (isChecked) {//如果已经选中再选的话就取消选中
                mCheckedPosition.put(position, false);
                mSelectedContacts.remove(contact);
            } else {
                mCheckedPosition.put(position, true);
                mSelectedContacts.add(contact);
            }
            mAdapter.notifyDataSetChanged();
            updateSelectedNum();//更新已经选中的群成员的数量
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ImConstants.REQUEST_CODE && resultCode == ImConstants.RESULT_CODE_EXIT) {
            finish();
        }
    }

    /**
     * 显示选择群成员列表的adapter
     */
    private class SelectMemberListAdapter extends BaseAdapter {
        private Context        mContext;
        private LayoutInflater mInflater;
        private List<Object>   mList;

        public SelectMemberListAdapter(Context context) {
            this.mContext = context;
            this.mInflater = LayoutInflater.from(context);
        }

        public void setData(List<Object> list) {
            this.mList = list;
        }

        public List<Object> getData() {
            return mList;
        }

        @Override
        public int getCount() {
            return mList == null ? 0 : mList.size();
        }

        @Override
        public Object getItem(int position) {
            return mList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Holder holder;
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.select_group_member_lsit_item, parent, false);
                holder = new Holder(convertView);
            } else {
                holder = (Holder) convertView.getTag();
            }
            //默认是同时显示分组标题和内容的
            holder.mRootView.setVisibility(View.VISIBLE);
            holder.mCharTv.setVisibility(View.GONE);
            Object object = mList.get(position);
            //此adapter用于显示ContactPerson
            if (object instanceof String) {
                //如果是分组的标题，只显示分组标题
                holder.mCharTv.setText(object.toString());
                holder.mRootView.setVisibility(View.GONE);
                holder.mCharTv.setVisibility(View.VISIBLE);
            } else if (object instanceof Contact) {
                if (isChecked(position)) {
                    holder.mCheckBox.setChecked(true);
                } else {
                    holder.mCheckBox.setChecked(false);
                }
                Contact contact = (Contact) object;
                holder.duty.setText(contact.getDuty());
                holder.mNameTv.setText(contact.getNickName());
                contact.showImageIcon(mContext, holder.mIcon, holder.mIconExpandTv);
            }
            //最后一行分割线不显示
            if (position == getCount() - 1) {
                holder.mLineView.setVisibility(View.GONE);
            } else if (position < getCount() - 1) {
                holder.mLineView.setVisibility(View.VISIBLE);
            }
            return convertView;
        }
    }

    private boolean isChecked(int position) {
        //这里返回的是引用类型，会自动转化成boolean类型,因此要判空
        Boolean checked = mCheckedPosition.get(position);
        if (checked == null) {
            return false;
        }
        return checked;
    }

    private class Holder {
        AvatarImageView mIcon;
        TextView        mIconExpandTv;
        TextView        mNameTv;
        TextView        duty;
        View            mRootView;
        TextView        mCharTv;
        CheckBox        mCheckBox;
        View            mLineView;

        public Holder(View view) {
            view.setTag(this);
            this.mIcon = (AvatarImageView) view.findViewById(R.id.select_member_item_icon);
            this.mIconExpandTv = (TextView) view.findViewById(R.id.select_member_item_icon_expand);
            this.mNameTv = (TextView) view.findViewById(R.id.select_member_item_name);
            this.duty = (TextView) view.findViewById(R.id.select_member_item_duty);
            this.mRootView = view.findViewById(R.id.select_member_item_root);
            this.mLineView = view.findViewById(R.id.select_member_item_line);
            this.mCheckBox = (CheckBox) view.findViewById(R.id.select_member_item_checkbox);
            this.mCharTv = (TextView) view.findViewById(R.id.select_member_item_char);
        }
    }
}
